<script setup>
import { onMounted, onUnmounted, ref } from 'vue'
import axios from 'axios'
import FingerprintJS from '@fingerprintjs/fingerprintjs'
import { useRouter } from 'vue-router'
import { login } from '@/api/userToService'
import { useCounterStore } from '@/stores/counter'
import { useIsSaveLocalStore } from '@/stores/isSaveLocalStore'
import image1 from '@/assets/images/125479966_p0_master1200.jpg'
import image2 from '@/assets/images/125474784_p0_master1200.jpg'
import imgae3 from '@/assets/images/画板 1.png'

const formRef = ref(null)
const router = useRouter()
const counterStore = useCounterStore()
const isSaveLocalStore = useIsSaveLocalStore()
const dialogTableVisible = ref(false)
const codeShow = ref(false)
const url = ref('')
const codeExistTime = ref(360)
// 存储所有光线的数组
const lights = ref([])
const form = ref({
  username: '',
  password: '',
})
const isLoading = ref(false)
const isAccelerated = ref(false)
const waveDiv = ref(null)
const loadingTime = ref(10)
const getDeviceId = async () => {
  try {
    const fp = await FingerprintJS.load()
    const result = await fp.get()
    return result.visitorId
  } catch {
    ElMessage.error('we can get your deviceID ')
  }

  return null
}
const getCodeImage = async () => {
  codeShow.value = !codeShow.value
  const nowTime = Date.now()
  const deviceID = await getDeviceId()
  try {
    // 发送请求获取二维码图片
    console.log('这里获得了唯一请求标识:' + `${nowTime + deviceID}`)
    const response = await axios.get('http://localhost:8080/wcCheck/wxLogin', {
      responseType: 'blob',
      headers: {
        token: `${nowTime}` + `${deviceID}`,
      },
    })
    const imageUrl = URL.createObjectURL(response.data)
    console.log(imageUrl)
    url.value = imageUrl
  } catch (error) {
    // 请求失败后的处理
    if (error.response) {
      // 请求已发出，服务器响应了状态码，但状态码超出了 2xx 范围
      console.error('Response error:', error.response)

      ElMessage.error(`Request failed with status: ${error.response.status}`)
    } else if (error.request) {
      // 请求已发出，但没有收到响应
      console.error('Request error:', error.request)
      ElMessage.error('No response received from the server.')
    } else {
      // 其他错误
      console.error('Error:', error.message)
      ElMessage.error(`Error occurred: ${error.message}`)
    }
  }

  const timer = setInterval(async () => {
    codeExistTime.value--

    if (codeExistTime.value === 30) {
      ElMessage.error('the code will be invalid after 30 seconds')
    }
    if (codeExistTime.value === 0) {
      codeExistTime.value = 360
      clearInterval(timer)
      ElMessage.error('the code has being invalid')
    }
    if (codeExistTime.value % 5 === 0) {
      try {
        const res = await axios.get('http://localhost:8080/wcCheck/wxUserGet', {
          headers: {
            token: `${nowTime}` + `${deviceID}`,
          },
        })
        console.log(res.data.result)
        if (res.data.result !== null && res.data.statuCode !== 0) {
          ElMessage.success('login pass')
          counterStore.Avatar = res.data.result.headimgurl
          counterStore.count = res.headers['token']
          clearInterval(timer)
          codeExistTime.value = 360
          codeShow.value = false
          router.push('/layout')
        }
      } catch (error) {
        if (error.result.status === 422) {
          ElMessage.error()
        }
      }
    }
  }, 1000)
}
/**
 * 提交
 */
const onSubmit = async () => {
  console.log('提交' + form.value.name + ';' + form.value.password)
  formRef.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.error('please input correct information')
      return
    }
    let timer = null
    try {
      isLoading.value = true
      timer = setInterval(() => {
        loadingTime.value--
        if (loadingTime.value === 0) {
          clearInterval(timer)
          isLoading.value = false
        }
      }, 1000)
      const res = await login(form.value)
      if (res.statuCode === 200) {
        ElMessage.success('Login success')
        counterStore.count = res.result
        router.push('/layout')
      } else if (res.statuCode === 201) {
        ElMessage.error(res.message)
      }
    } catch (error) {
      ElMessage.error('Login failed')
    } finally {
      isLoading.value = false
      clearInterval(timer)
      loadingTime.value = 10
    }
  })
}

const toRegin = () => {
  router.push('/regin')
}
const rules = ref({
  username: [
    {
      required: true,
      message: '请输入用户名',
      trigger: 'blur',
    },
    {
      min: 3,
      max: 20,
      message: '长度在 3 到 20 个字符',
      trigger: 'blur',
    },
  ],
  password: [
    {
      required: true,
      message: '请输入密码',
      trigger: 'blur',
    },
    {
      min: 3,
      max: 20,
      message: '长度在 3 到 20 个字符',
      trigger: 'blur',
    },
  ],
})

const toggleSpeed = () => {
  if (isAccelerated.value) {
    // 如果已加速，恢复到原来的速度
    waveDiv.value.style.animationDuration = '5s'
  } else {
    // 如果未加速，加速到 2 秒
    waveDiv.value.style.animationDuration = '3s'
  }
  isAccelerated.value = !isAccelerated.value
}
// 监听鼠标移动事件
const updateLightPosition = (event) => {
  const mouseX = event.clientX
  const mouseY = event.clientY

  // 随机改变光线的尺寸
  const size = Math.random() * 30

  // 随机生成一个颜色
  const color = `hsl(${Math.random() * 360}, 100%, 70%)`

  // 创建新的光线
  const newLight = {
    style: {
      width: `${size}px`,
      height: `${size}px`,
      left: `${mouseX - size / 2}px`,
      top: `${mouseY - size / 2}px`,
      background: `radial-gradient(circle, ${color} 0%, rgba(255, 255, 255, 0) 70%)`,
      position: 'absolute',
      borderRadius: '50%',
      pointerEvents: 'none',
      opacity: 1,
      transition:
        'transform 0.1s ease-out, opacity 0.8s ease-out, width 0.8s ease-out, height 0.8s ease-out',
    },
    timestamp: Date.now(), // 时间戳用于后续删除过期的光线
  }
  setInterval(() => {
    const currentTime = Date.now()
    lights.value = lights.value.filter((light) => currentTime - light.timestamp < 500) // 保持光线1秒钟
  }, 100)
  // 将新光线加入数组
  lights.value.push(newLight)

  // 删除已经消失的光线，防止数组无限增长
  lights.value = lights.value.filter((light) => Date.now() - light.timestamp < 60) // 保持光线1秒钟
}

// 在组件挂载时添加鼠标移动事件监听器
onMounted(() => {
  window.addEventListener('mousemove', updateLightPosition)
})

// 在组件卸载时移除事件监听器
onUnmounted(() => {
  window.removeEventListener('mousemove', updateLightPosition)
})
</script>

<template>
  <el-dialog v-model="dialogTableVisible" width="500">
    <div
      style="
        height: 488px;
        display: flex;
        justify-content: center;
        align-items: center;
        position: relative;
        flex-direction: column;
      "
    >
      <div style="font-size: 24px; margin-bottom: 15px">QR code login</div>
      <el-image :src="url" fit="fill" style="width: 300px; height: 300px" />
      <div style="position: absolute; bottom: 6%">
        <el-button @click="getCodeImage">
          <div v-if="codeShow">after {{ codeExistTime }} seconds the code become invalid</div>
          <div v-else>click here to get code</div>
        </el-button>
      </div>
    </div>
  </el-dialog>
  <div v-for="(light, index) in lights" :key="index" :style="light.style" class="light"></div>
  <el-container style="height: 100%; overflow: hidden">
    <el-header style="height: 150px; border-radius: 5px 5px 0 0; position: relative">
      <div ref="waveDiv" class="movie_lao" @click="toggleSpeed">
        <el-image :src="imgae3" style="width: 450px; height: 200px" />
      </div>
    </el-header>
    <el-container>
      <el-aside style="height: 100%; width: 600px; overflow: hidden">
        <div style="width: 100%; height: 100%">
          <div style="margin-bottom: 20px">
            <el-carousel
              :autoplay="true"
              class="delay"
              direction="vertical"
              height="347px"
              motion-blur
              style="border-radius: 5px 5px 5px 5px"
            >
              <el-carousel-item>
                <el-image
                  :src="image1"
                  style="width: 100%; opacity: 1; border-radius: 5px 5px 5px 5px"
                />
              </el-carousel-item>
              <el-carousel-item>
                <el-image
                  :src="image2"
                  style="width: 100%; opacity: 1; border-radius: 5px 5px 5px 5px; object-fit: cover"
                />
              </el-carousel-item>
            </el-carousel>
          </div>

          <el-carousel
            :autoplay="true"
            class="move"
            height="347px"
            motion-blur
            style="border-radius: 5px 5px 5px 5px"
          >
            <el-carousel-item>
              <el-image
                :src="image1"
                style="width: 100%; border-radius: 5px 5px 5px 5px; opacity: 1"
              />
            </el-carousel-item>
            <el-carousel-item>
              <el-image :src="image2" style="width: 100%; opacity: 1" />
            </el-carousel-item>
          </el-carousel>
        </div>
      </el-aside>
      <el-main
        style="
          overflow: hidden;
          height: 100%;
          width: 100%;
          display: flex;
          justify-content: center;
          align-items: center;
        "
      >
        <div
          class="movie"
          style="
            opacity: 0.9;
            height: 500px;
            width: 500px;
            background-color: rgb(212, 234, 247);
            border-radius: 24px;
            display: flex;
            justify-content: center;
            align-items: center;
            position: relative;
          "
        >
          <div class="toBorder"></div>
          <div
            style="
              position: absolute;
              top: 20px;
              font-size: 50px;
              letter-spacing: 20px;
              text-shadow:
                1px 1px rgb(212, 234, 247),
                0 0 25px rgba(255, 255, 255, 0.7);
            "
          >
            LOGIN
          </div>
          <el-form ref="formRef" :model="form" :rules="rules" style="position: relative">
            <el-form-item
              label="Activity name"
              label-position="top"
              label-width="auto"
              prop="username"
              style="max-width: 400px"
            >
              <el-input v-model="form.username" placeholder="input your name" />
            </el-form-item>
            <el-form-item
              label="Activity password"
              label-position="top"
              label-width="auto"
              prop="password"
              style="max-width: 400px"
            >
              <el-input v-model="form.password" placeholder="input your password" />
            </el-form-item>
            <el-form-item>
              <el-checkbox v-model="isSaveLocalStore.isSave" label="Remember me" />
            </el-form-item>
            <div style="display: flex; justify-content: center; align-items: center">
              <el-button :disabled="isLoading" type="primary" @click="onSubmit">
                <span v-if="isLoading">Loading...</span>
                <span v-else>submit</span>
              </el-button>
            </div>
          </el-form>
          <div style="position: absolute; bottom: 10%; left: 10%">
            <el-link style="font-size: large" type="primary" @click="toRegin">Regin</el-link>
          </div>
          <div style="position: absolute; bottom: 10%; right: 10%">
            <el-link style="font-size: large" type="primary" @click="router.push('/layout')"
              >To the home page
            </el-link>
          </div>
          <div style="position: absolute; bottom: 25%; left: 10%">
            <el-link
              style="font-size: large"
              type="primary"
              @click="dialogTableVisible = !dialogTableVisible"
              >QR code login
            </el-link>
          </div>
        </div>
      </el-main>
    </el-container>
  </el-container>
</template>

<style scoped>
@import url('../assets/css/Home.css');
</style>
